<template>
  <div  class="wrap">
    <h1>欢迎登录</h1>
   <van-form @submit="onSubmit">
  <van-field
    v-model="username"
    name="username"
    label="用户名"
    placeholder="用户名"
    :rules="[{ required: true, message: '请填写用户名' }]"
  />
  <van-field
    v-model="password"
    type="password"
    name="pwd"
    label="密码"
    placeholder="密码"
    :rules="[{ required: true, message: '请填写密码' }]"
  />
  <div style="margin: 16px;" class="footsub">
    <van-button   block type="info" native-type="submit">登录</van-button>
    </div>
</van-form>
<!-- 注册 -->
   <van-button @click="$router.push('/register')" class="register" type="primary" block >注册</van-button>
  </div>
</template>

<script>
import { doLogin } from '@api'
import { Toast } from 'vant'
export default {
  data () {
    return {
      username: '',
      password: ''
    }
  },
  methods: {
    onSubmit (params) {
      doLogin({
        ...params,
        deviceId: '11',
        deviceName: '手机'
      }).then(res => {
        if (res.data.code === 0) {
          // 存储token
          localStorage.setItem('token', res.data.data.token)
          // console.log(res)
          // 请求成功弹出注册成功的信息 并跳转至登录页
          Toast.loading({
            type: 'success',
            message: '登录成功',
            onClose: () => {
              if (this.$route.query.from) {
                this.$router.replace(this.$route.query.from)
              } else {
                this.$router.replace('/home')
              }
            }
          })
        } else {
          Toast.loading({
            type: 'fail',
            message: '登录失败'
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
h1{
  text-align: center;
}
.footsub{
  display: flex;
}
.van-button--block {
  width: 80%;
}
.register{
 margin-left: 15px;
 width: 74%;
}
</style>
